package com.ydc.service;


import com.ydc.vo.ImageVO;
import org.springframework.beans.factory.annotation.Value;


import org.springframework.context.annotation.PropertySource;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@PropertySource(value = "classpath:/properties/image.properties",encoding = "utf-8")
class FileServiceImpl implements FileService {

    @Value("${image.localPath}")
    private String localPath;//  ="D:/ydcDir";
    @Value("${image.localUrlPath}")
    private String localUrlPath;//  ="http://image.ydc.com";

    /**
     * 文件上传案例实现
     * 1.如何保证前端上传的数据是有效的
     * 1.1检验文件的名称检查是否为图片
     * 1.2校验是否为恶意的程序
     *
     * @return
     */
    @Override
    public ImageVO upload(MultipartFile file) throws IOException {
        //校验是否为图片类型
        String fileName = file.getOriginalFilename();
        fileName = fileName.toLowerCase();
        if (!fileName.matches("^.+\\.(jpg|png|gif|jpeg)$")) {//正则表达式  .表示任意单个字符
            return null;
        }

        //校验图片类型是否为木马
        BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        if (width == 0 || height == 0) {
            return null;
        }

        //实现文件上传
        //实现分目录存储  可以以时间维度进行分割  /yyyy/MM/dd/

        String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());

        //进行目录拼接
        String localDir = localPath + datePath;
        //需要创建目录
        File dirfile = new File(localDir);
        if (!dirfile.exists()) {
            dirfile.mkdirs();
        }

        //文件名称重复 采用uuid防止文件重名
        String uuid = UUID.randomUUID().toString().replace("_", "");
        String filetype = fileName.substring(fileName.lastIndexOf("."));
        String realfileName = uuid + filetype;
        String fileAll = localDir + realfileName;
        File realFile = new File(fileAll);
        file.transferTo(realFile);

        String virtualPath = datePath + realfileName;
        //
        String urlPath = localUrlPath + virtualPath;
        return new ImageVO(virtualPath, urlPath, realfileName);
    }

    @Override
    public void fileRemove(String virtualPath) {
        String filePath = localPath + virtualPath;
        File file = new File(filePath);
        file.delete();
    }




}
